<?php

namespace app\system\controller\product;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;


class Code extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['code', 'name'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\product\Code();
    }



    public function getElement(){
        $param = $this->request->param();
        $code = db::name('product_code')->where(['hs_code' => $param['hs_code']])->find();
        $element = $code ? $code['element'] : '';
        $element = explode("\n", $element);
        $element_arr = array_filter(array_unique($element));
        $element = [];
        foreach($element_arr as $val){
            $element[] = [
                'name' => $val,
                'value' => '',
            ];
        }

        if(!empty($param['product_id'])){
            $product = db::name('product')->where(['id' => $param['product_id']])->find();
        }

        $this->success('', $element);
    }



    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->alias($alias)
            ->where($where);



        $res = $res->order($order)->paginate($limit);

        $list = $res->items();

        foreach($list as &$val){
            $val['name'] = empty($val['name']) ? null : html_entity_decode($val['name']);
            $val['element'] = empty($val['element']) ? null : html_entity_decode($val['element']);
            $val['code_name'] = $val['hs_code'] . '(' . $val['name'] . ')';
        }


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();


            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            if(empty($data['hs_code'])) $this->error(__('请输入') . __('HS CODE'));
            if(empty($data['name'])) $this->error(__('请输入') . __('商品名称'));
            if(empty($data['element'])) $this->error(__('请输入') . __('报关要素'));


            $result = false;
            $this->model->startTrans();
            try {
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }



        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();


            $data   = $this->excludeFields($data);
            if(empty($data['hs_code'])) $this->error(__('请输入') . __('HS CODE'));
            if(empty($data['name'])) $this->error(__('请输入') . __('商品名称'));
            if(empty($data['element'])) $this->error(__('请输入') . __('报关要素'));


            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $row['name'] = empty($row['name']) ? null : html_entity_decode($row['name']);
        $row['element'] = empty($row['element']) ? null : html_entity_decode($row['element']);


        $this->success('', [
            'row' => $row
        ]);
    }































}